/**------------------------------页面数据------------------------------------------ */
// 全局变量
// 是否购买卡片
let isBuyFlag = false
// 需要补充的元素下标
let elementIndex = 0

// 五个等级的卡片
const heroList1 = heroList.filter(item => item.grade === 1)
const heroList2 = heroList.filter(item => item.grade === 2)
const heroList3 = heroList.filter(item => item.grade === 3)
const heroList4 = heroList.filter(item => item.grade === 4)
const heroList5 = heroList.filter(item => item.grade === 5)

const lvToHero = new Map([[1, heroList1], [2, heroList2], [3, heroList3], [4, heroList4], [5, heroList5]])



/**---------------------------数据驱动页面----------------------------------- */

// 根据概率获取卡片
function getCateCard() {
  const res = []
  const c1 = getTextNode(".lv1").replace("%", "") / 100
  const c2 = getTextNode(".lv2").replace("%", "") / 100
  const c3 = getTextNode(".lv3").replace("%", "") / 100
  const c4 = getTextNode(".lv4").replace("%", "") / 100
  const c5 = getTextNode(".lv5").replace("%", "") / 100
  const chanceResult = getChanceResult(c1, c2, c3, c4, c5)
  chanceResult.forEach(item => {
    const tempArr = lvToHero.get(item)
    res.push(tempArr[random(tempArr.length)])
  })
  const a = res.sort((a, b) => a.grade - b.grade)
  console.log(a)
  return a
}

// 渲染函数(下面五个框)
function render(data, flag, index = 0) {
  const nodes = document.querySelectorAll(".hero-box")
  if (flag) {
    nodes[index].children[0].className = "disappear"
    nodes[index].children[1].className = "disappear"
  } else {
    nodes.forEach((node, index) => {
      node.className = "hero-box " + data[index].className
      node.children[0].src = data[index].path
      node.children[0].className = ""
      const infoElement = node.children[1]
      infoElement.className = "info"
      infoElement.children[0].innerText = data[index].name
      const coinElement = infoElement.children[1]
      coinElement.children[1].innerText = data[index].grade
    })
  }
}

// 劫持heroMarket
const cardListProxy = new Proxy( { cardList: null } , {
  get(target, prop) {
    console.log("cardList被读取")
    return target[prop]
  },
  set(target, prop, newValue) {
    console.log("cardList被修改")
    target[prop] = newValue
    render(newValue, isBuyFlag, elementIndex)
  }
})

// 更新数据
function update() {
  cardListProxy.cardList = getCateCard()
}
// 初始化
update()

/**-----------------------购买经验，刷新按钮逻辑---------------------------- */

// 根据当前经验渲染进度条，rate为当前经验与总经验的比率
function renderProgressBar(rate) {
  const count = Math.floor(rate.toFixed(2) * 100)
  const divNodes = [...document.querySelectorAll(".progress-bar>div")]
  divNodes.forEach(node => {
    node.style.backgroundColor = "rgba(0, 0, 0, .5)"
  })
  divNodes.some((node, index) => {
    if (index === count) return true
    node.style.backgroundColor = "#bafff8"
  })
}

// 余额扣费逻辑
function checkCoin(cost) {
  return new Promise((resolve, reject) => {
    const coinSelector = ".top>.coin-box>span"
    if (getTextNode(coinSelector) - cost < 0) {
      return createDialog("金币不足~")
    }
    patchTextNode(coinSelector, getTextNode(coinSelector) - cost)
    resolve()
  })
}

// 修改概率逻辑
function changeChance(chanceArr) {
  chanceArr.forEach((item, index) => {
    patchTextNode(`.lv${index+1}`, Math.floor(item * 100) + "%")
  })
}

// 等级增加逻辑
function lvExpAdd() {
  let lv = getTextNode(".lv").replace("级", "") - 0
  let currentExp = getTextNode(".exp>.b1") - 0
  let totalExp = getTextNode(".exp>.b2") - 0
  // 新值
  let newCurrentExp = currentExp + 4
  let newLv = lv
  let newTotalExp = totalExp
  if (newCurrentExp >= totalExp) {
    newLv++
    newCurrentExp = newCurrentExp - totalExp
    newTotalExp = lvToExp.get(newLv).exp
    changeChance(lvToExp.get(newLv).chance)
  }
  patchTextNode(".lv", newLv + "级")
  patchTextNode(".exp>.b1", newCurrentExp)
  patchTextNode(".exp>.b2", newTotalExp)
  renderProgressBar(newCurrentExp / newTotalExp)
}

// 刷新按钮逻辑
const refreshBtn = document.querySelectorAll(".opera-box")[1]
refreshBtn.addEventListener("click", async () => {
  await checkCoin(2)
  update()
})

// 购买经验按钮逻辑
const buyExpBtn = document.querySelectorAll(".opera-box")[0]
buyExpBtn.addEventListener("click", async () => {
  await checkCoin(4)
  lvExpAdd()
})

/**--------------购买卡片逻辑----------------- */

// 创建小星星标识的函数, count表示创建小星星的个数
function createStarsDiv(count) {
  const divStarsEl = createDOM("div", { className: "stars" })
  // 创建小星星，并将小星星放入div
  for (let i = 0; i < count; i++) {
    // 开发环境
    // const iconStarEl = createDOM("img", { className: "star-icon", src: "../icons/star1.png" })
    // 生产环境
    const iconStarEl = createDOM("img", { className: "star-icon", src: "/jcc/icons/star1.png" })
    divStarsEl.appendChild(iconStarEl)
  }
  return divStarsEl
}


// 渲染将英雄渲染到展示区域
function heroToShow(heroData) {
  const heroAreas = [...document.querySelectorAll(".hero-card")]
  heroAreas.some((item, index) => {
    if (!!item.className.slice(9)) return false
    heroAreas[index].className = "hero-card " + heroData.className
    const imgEl = createDOM("img", { className: "hero-img", src: heroData.path })
    heroAreas[index].appendChild(imgEl)
    // 添加星标
    heroAreas[index].appendChild(createStarsDiv(heroData.grade))
    return true
  })
  console.log(heroData)
}

// 购买
const heroBoxNodes = document.querySelectorAll(".hero-box")

heroBoxNodes.forEach((node, index) => {
  node.addEventListener("click", async () => {
    if (node.children[1].className === "disappear") return createDialog("这块已经没有东西了~")
    const heroAreas = [...document.querySelectorAll(".hero-card")]
    const isFull = heroAreas.every(item => !!item.className.slice(9))
    if (isFull) return createDialog("展示区域已满~")
    isBuyFlag = true

    // 花费处理
    const coin = cardListProxy.cardList[index].grade
    await checkCoin(coin)
    
    // 将卡片渲染到展示区域
    heroToShow(cardListProxy.cardList[index])
    
    // 更新代理对象
    elementIndex = index
    cardListProxy.cardList = cardListProxy.cardList.map((item, indey) => {
      if (indey === index) item = {}
      return item
    })
    isBuyFlag = false
  })
})